import React, {Component} from 'react';
import {connect} from 'dva';
import {
  Form, Input, Select, Button, Radio, Steps, Checkbox, DatePicker, InputNumber, Icon, Switch, TreeSelect, message
} from 'antd';
import PartmentButton from "../../../components/PartmentButton";
import '../Task.less';
import {
  getTreeperBydepart, //部门人员
  taskGetStepThreeDetail,
  taskSaveStepThreeDetail
} from "../../../services/api";
import bcx_utils from '../../../common/bcx_utils';

const FormItem = Form.Item;
const {Option} = Select;
const {Step} = Steps;
const {RangePicker} = DatePicker;


@connect(state => ({
  profile: state.profile,
}))


@Form.create()

export default class Information extends Component {

  state = {
    visibleuser: false,
    selectedTags: [],
    arrayObj: [],
    treeData: [],
    comTaskId: this.props.dataSource.comTaskId || "",
    perNum: '',//任务所需人数
    pagenav: {
      checkedkeys: [],
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = current;
        pagenav.pageSize = pageSize;
        this.setState({pagenav});
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({pagenav});
        setTimeout(() => {
          this.bbdExampersonPage();
        });
      },
      total: 0,
    }
  }

  componentWillMount() {
    let dataSource = this.props.dataSource;
    if (dataSource.comTaskId != undefined) {
      this.setState({
        comId: dataSource.comTaskId
      }, () => {
        this.taskGetStepThreeDetail()
      });
    }
    this.getTreeperBydepart();
  }

  handleSubmit = (e, type) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log(values);
        if (values.taskPerArray.length > values.perNum) {
          bcx_utils.preventRA((resolve) => {
            message.error("参与人员数不能大于所需人数", 1.5, () => resolve());
          });
          return;
        }
        //是否暂存， isFB 为 0 时候暂存。
        values.isFB = type || '1';
        values.comTaskId = this.state.comTaskId;
        values.chargePerName = this.state.chargePerName;
        let newTaskPerArray = values.taskPerArray.reduce((acc, item) => acc.concat(item.replace(/(dept)/, "")), []);
        const ajaxData = {...values, ...{newTaskPerArray}};
        this.taskSaveStepThreeDetail(values);
      }
    });
  };

  //部门人员
  getTreeperBydepart = () => {
    getTreeperBydepart().then(
      response => {
        console.log(response, "response-部门人员-getTreeperBydepart");
        this.setState({treeData: response.data});
      },
      err => {
        console.log(err, "err-部门人员-getTreeperBydepart");
      }
    );
  };
  //获取详情
  taskGetStepThreeDetail = () => {
    console.log('获取任务详情 任务Id:', this.state.comTaskId)
    taskGetStepThreeDetail({comTaskId: this.state.comTaskId}).then(
      response => {
        console.log(response, "response-获取详情-taskGetStepThreeDetail");
        if (response.data) {
          const {
            chargePerId,
            chargePerName,
            taskPerArray,
            taskPerInsMode,
            perNum
          } = response.data;

          this.setState({
            chargePerId,
            checkedkeys: chargePerId,
            chargePerName,
            taskPerArray,
            taskPerInsMode,
            perNum
          });
        }
      },
      err => {
        console.log(err, "err-获取详情-taskGetStepThreeDetail");
      }
    );
  };
  //提交表单第三步
  taskSaveStepThreeDetail = (values) => {
    console.log('提交表单第三步', values)
    taskSaveStepThreeDetail(values).then(
      response => {
        console.log(response, "response-提交表单-taskSaveStepThreeDetail");
        //传递保险信息
        if (values.isFB === '1') {
          const {taskPerInsMode} = values;

          if (values.taskPerInsMode === '1') {
            this.props.history.push(
              {
                pathname: `/taskmanager/tasksuccess`,
                state: {securityDatas: {...response.data || "", ...{taskPerInsMode}}}
              }
            );
            console.log('传递成功')
          } else if (values.taskPerInsMode === '2') {
            this.props.history.push(
              {
                pathname: `/taskmanager/tasksuccess`,
                state: {securityDatas: {...response.data || "", ...{taskPerInsMode}}}
              }
            );
            console.log('传递成功')
          }

        }

      },
      err => {
        console.log(err, "err-提交表单-taskSaveStepThreeDetail");
      }
    );
  };
  callback = (key) => {
    console.log(key);
  };

  handleChange(tag, checked) {
    const {selectedTags} = this.state;
    const nextSelectedTags = checked ?
      [...selectedTags, tag] :
      selectedTags.filter(t => t !== tag);
    console.log('You are interested in: ', nextSelectedTags);
    this.setState({selectedTags: nextSelectedTags});
  }

  /* 验证手机号码 */
  checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };
  handleCancel = () => {
    console.log('cancle');
  }


  render() {
    const {getFieldDecorator} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    return (
      <div className="CreateTask">
        <div className="Steps">
          <Steps current={2}>
            <Step title="基本信息"/>
            <Step title="出勤设置"/>
            <Step title="发布设置"/>
          </Steps>
        </div>
        <Form
          onSubmit={this.handleSubmit}
          style={{marginTop: 24}}
        >
          <FormItem
            {...formItemLayout}
            label="任务负责人"
          >
            {getFieldDecorator('chargePerId', {
              initialValue: this.state.chargePerId,
              rules: [{
                required: true, message: '请输入任务负责人',
              }],
            })(
              <div className="fjr">
                <div className="row">
                  <Button type="primary" onClick={() => {
                    this.setState({visibleuser: true});
                  }} ghost>选择人员</Button> <span className="exclamation"><Icon type="exclamation-circle"/>人数限制：1人</span>
                </div>

                <div className="fjr-list">
                <span>负责人:<Icon type="user"/>
                  {this.state.chargePerName}
                </span>
                </div>
              </div>
            )}
          </FormItem>
          {/*  <div className="card">全网推送规则</div>
          <FormItem
            {...formItemLayout}
            label="设置共享区域"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <Select placeholder="请选择">
                <Option value="xiao">付晓晓</Option>
                <Option value="mao">周毛毛</Option>
              </Select>
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="设置共享人数"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <InputNumber min={1} max={10} />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="中心扩散范围"
          >
            {getFieldDecorator('address', {
              rules: [{ required: true, message: '请选择' }],
            })(
              <Input />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="共享起止时间"
          >
            {getFieldDecorator('dateRange', {
              rules: [{ required: true, message: '请选择生效日期' }],
            })(
              <RangePicker placeholder={['开始日期', '结束日期']} style={{ width: '100%' }} />
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="任务性质"
            style={{ marginBottom: 0 }}
          >
            {getFieldDecorator('branch', {
              rules: [{
                required: true, message: '请选择',
              }],
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">固定价位(元/人) <Input style={{ display: "block" }} placeholder="请输入" /> </Radio>
                <Radio className="radioStyle" value="2">时长计价(元/小时) <Input style={{ display: "block" }} placeholder="请输入" /> </Radio>
              </Radio.Group>
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="任务投保"
          >
            {getFieldDecorator('branch', {
              rules: [{
                required: true, message: '请选择',
              }],
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">需个人购买 <span className="exclamation"><Icon type="exclamation-circle" />适用于：团队任务</span></Radio>
                <Radio className="radioStyle" value="2">企业赠送保险</Radio>
                <Radio className="radioStyle" value="3">无需投保</Radio>
              </Radio.Group>
              )}
          </FormItem> */}
          <div className="card">推送给内部员工</div>
          <FormItem
            {...formItemLayout}
            label="选择参与人员"
          >
            {getFieldDecorator('taskPerArray', {
              initialValue: this.state.taskPerArray,
              rules: [{
                required: true, message: '请选择参与人员'
              }],
            })(
              <TreeSelect
                treeData={this.state.treeData}
                treeCheckable
                onChange={perIdStr => {
                  console.log(perIdStr, "perIdStr-onChange");
                }}
                showCheckedStrategy={TreeSelect.SHOW_CHILD}
                searchPlaceholder={"选择部门或人员"}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="所需人数">
            {getFieldDecorator("perNum", {
              initialValue: this.state.perNum,
              rules: [{
                pattern: /^[1-9][0-9]*$/,
                required: true, message: "请选择所需人数"
              }]
            })(<InputNumber min={1} max={1000000000}/>)}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="任务投保"
          >
            {getFieldDecorator('taskPerInsMode', {
              initialValue: this.state.taskPerInsMode,
              rules: [{
                required: true, message: '请选择任务投保',
              }],
            })(
              <Radio.Group>
                <Radio className="radioStyle" value="1">企业赠送保险 </Radio>
                <Radio className="radioStyle" value="2">无需投保</Radio>
              </Radio.Group>
            )}
          </FormItem>
          {/*  <FormItem
            {...formItemLayout}
            label="开关控制"
          >
            <div className="Switch-box">
              <div>任务实名啐证:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>参与人员上报:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>任务轨迹上报:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>热力图呈现:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
              <div>任务步数记录:<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked /></div>
            </div>
          </FormItem> */}
          <FormItem {...submitFormLayout} style={{marginTop: 32}}>
            <Button onClick={() => {
              this.props.switchStep(-1)
            }}>上一步</Button>
            <Button style={{marginLeft: 8}} onClick={(e) => {
              this.handleSubmit(e, "0");
            }}>暂存</Button>
            <Button type="primary" style={{marginLeft: 8}} htmlType="submit">确认发布</Button>
          </FormItem>
        </Form>

        {this.state.visibleuser && <PartmentButton onCheck={(checkedkeys, arrayObj) => {
          console.log(checkedkeys, 'createpublish');
          this.setState({visibleuser: false, checkedkeys});
          arrayObj.length != 0 && this.setState({chargePerName: arrayObj[0].title});

          const {setFieldsValue} = this.props.form;
          setFieldsValue({chargePerId: checkedkeys});
        }} value={this.state.checkedkeys} visible={this.state.visibleuser} type={'radio'}
                                                   handleCancel={this.handleCancel}/>}
      </div>
    );
  }
}

